/**
 *
 */
package com.wedroid.api.web.controller;

import java.util.Collections;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.wedroid.api.handler.HashidsDecoder;
import com.wedroid.api.handler.ResourceHandler;
import com.wedroid.api.mapper.ContacterMapper;
import com.wedroid.api.service.ContacterService;
import com.wedroid.entity.contact.Contacter;

/**
 * @author lute
 */
@Controller
@RequestMapping("")
public class ContacterController {

    @Autowired
    private HashidsDecoder decoder;

    @Autowired
    private ResourceHandler resourceHandler;

    @Autowired
    private ContacterService contacterService;

    /**
     * @param hashid
     * @return
     */
    @ResponseBody
    @RequestMapping("/contacters/{hashid}")
    public String getContacter(@PathVariable("hashid") String hashid) {

        Result result = new Result();

        // Decode hashid
        Optional<Long> decodedId = decoder.decode(hashid);
        if (decodedId.isPresent()) {

            Long id = decodedId.get();
            Contacter contacter = contacterService.load(id);

            // Transform contacter for JSON serialization
            ContacterMapper contacterMapper =
                    Collections.singletonList(contacter)
                               .stream()
                               .map(ContacterMapper::new)
                               .map(item -> item.resolveUrl(resourceHandler))
                               .collect(Collectors.toList())
                               .get(0);

            result.success().data("contacter", contacterMapper);
        } else {
            result.fail().message("INVALID_INDENTIFIER");
        }

        return JsonUtils.toJsonString(result);
    }

}
